const tencentcloud = require('tencentcloud-sdk-nodejs');
const { clientConfig, mergeAgent, logger } = require('../utils');

const EssbasicClient = tencentcloud.essbasic.v20210526.Client;

const client = new EssbasicClient(clientConfig);


module.exports = (app) => {
  // 获取模板列表
  app.post(`${process.env.VUE_APP_BASE_API}/template/describeTemplates`, async (req, res) => {
    const { userInfo, body } = req;
    const targetUser = userInfo;
    if (targetUser) {
      const { withPreviewUrl = true, templateName = '', limit = 10, offset = 0, tenantTemplateType = 0 } = body;
      const params = {
        Agent: mergeAgent({
          ProxyOrganizationOpenId: targetUser.organizationOpenId,
          OpenId: targetUser.openId,
        }),
        Version: '2021-05-26',
        WithPreviewUrl: withPreviewUrl, // 是否获取模板预览链接
        TemplateName: templateName,
        Limit: limit,
        Offset: offset,
      };
      try {
        const templateRes = await client.DescribeTemplates(params);
        if (templateRes.code === 'ResourceNotFound.Template') {
          // 处理没有模板的情况
          return res.json({
            code: 20000,
            data: { Templates: [] },
          });
        }
        // 有模板的情况，需要每个模板加企业的模板类型
        let allTemplates = [];
        if (templateRes?.Templates?.length) {
          // 处理模版新增模版合同类型字段
          allTemplates = templateRes?.Templates?.sort((a, b) => b.CreatedOn - a.CreatedOn)?.map((item) => {
            const enterpriseArr = item?.Recipients?.filter(f => f.RecipientType === 'ENTERPRISE') || [];
            const personArr = item?.Recipients?.filter(f => f.RecipientType === 'INDIVIDUAL') || [];
            let tempType = 0;
            if (enterpriseArr.length === 2 && personArr.length === 0) {
              tempType = 1; // BtoB
            } else if (enterpriseArr.length === 1 && personArr.length > 0) {
              tempType = 2; // BtoC
            } else if (enterpriseArr.length === 0 && personArr.length > 0) {
              tempType = 3; // toC
            }
            return {
              ...item,
              tenantTemplateType: tempType,
            };
          });
          const filterTemplates = tenantTemplateType ? allTemplates.filter(f => f.tenantTemplateType === tenantTemplateType) : [...allTemplates];
          return res.json({
            code: 20000,
            data: {
              ...templateRes,
              Templates: filterTemplates,
            },
          });
        }
        return res.json({
          code: 20000,
          data: templateRes,
        });
      } catch (error) {
        logger.error({
          ...params,
          Action: 'CreateConsoleLoginUrl',
          message: error.message,
          stack: error.stack,
        });
        if (error.code === 'ResourceNotFound.Template') {
          // 处理没有模板的情况
          return res.json({
            code: 20000,
            data: { Templates: [] },
          });
        }
        return res.json({
          code: 20400,
          massage: error,
        });
      }
    } else {
      res.json({
        code: 500,
      });
    }
  });
};
